<template>
  <div v-bind="$attrs" class="ttt-more">
    <slot />
    <div v-if="isMore" class="w100p d-f jc-c ai-c" ref="moreIconDom">
      <slot name="loading">
        <t-loading-icon />
      </slot>
    </div>
    <div v-else class="w100p d-f jc-c ai-c">
      <slot name="loaded">
        {{ $t('index.noMore') }}
      </slot>
    </div>
  </div>
</template>

<script setup lang="ts">
import TLoadingIcon from '../TLoadingIcon/TLoadingIcon.vue'
import { onMounted, ref } from 'vue'
import type { PropType } from 'vue'
import type { TMoreBeforeLoadParams } from '../types/components'

const props = defineProps({
  beforeLoad: {
    type: Function as PropType<TMoreBeforeLoadParams>,
    required: true,
    default: null
  }
})

// 更多DOM
const moreIconDom = ref<HTMLElement>()
// 是否还有更多
const isMore = ref<boolean>(true)

// 初始化加载
const initMore = () => {
  const observer = new IntersectionObserver((entries) => {
    if (entries[0].isIntersecting) {
      props.beforeLoad && props.beforeLoad((done: boolean) => {
        if (!done) {
          moreIconDom.value && observer.unobserve(moreIconDom.value)
          isMore.value = false
        }
      })
    }
  })
  moreIconDom.value && observer.observe(moreIconDom.value)
}

onMounted(() => {
  initMore()
})
</script>

<style scoped lang="scss">

</style>
